/**
 * Project Name:xk-ch-weixin-server <br/>
 * File Name:OkHttpUtils.java <br/>
 * Package Name:com.xikang.ch.cloudweix.utils <br/>
 * Date:2016年7月20日 下午2:46:56 <br/>
 * Copyright (c) 2016, Xikang All Rights Reserved.
 */

package com.ylkj.wx.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import okhttp3.FormBody;
import okhttp3.FormBody.Builder;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Http操作方法集合.
 *
 * @author tian-m
 * @date 2016年7月20日 下午2:46:56
 */
public class OkHttpUtils {

    private static final OkHttpClient client;

    private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpUtils.class);

    private static final String STATUS_CODE = "HTTP STATUS CODE:";

    public static final MediaType MEDIA_TYPE_MARKDOWN =
            MediaType.parse("text/x-markdown; charset=utf-8");

    static {
        client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
    }

    /**
     * Get方式访问微信API.
     * 
     * @param url 微信接口API路径
     * @return 获取到的信息
     * @throws IOException
     * @author tian-m
     * @date 2016年7月20日 下午4:19:05
     */
    public static String getContentByGet(String url) throws IOException {
        String result = "";

        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            LOGGER.info("status is " + response.code());
            if (response.isSuccessful()) {
                result = response.body().string();
            }
        }
        return result;
    }

    /**
     * http post 请求.
     * 
     * @param url 请求地址
     * @param parameters 请求参数
     * @return
     * @author tian-m
     * @date 2016年7月20日 下午4:19:36
     */
    public static String post(String url, Map<String, String> parameters) {
        String result = "";

        Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }

        RequestBody body = builder.build();
        Request request = new Request.Builder().url(url).post(body).build();
        try (Response response = client.newCall(request).execute();
                InputStream inputStream = response.body().byteStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));) {
            LOGGER.debug(STATUS_CODE + response.code());
            StringBuilder buffer = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                buffer.append(str);
            }
            result = buffer.toString();
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return result;
    }

    /**
     * http post 请求.
     * 
     * @param url 请求地址
     * @param s 请求参数
     * @return
     * @throws IOException
     * @throws ExecutionException
     * @throws InterruptedException
     * @author tian-m
     * @date 2016年7月20日 下午4:41:03
     */
    public static String post(String url, String s)
            throws IOException, ExecutionException, InterruptedException {
        String result = "";

        RequestBody body = RequestBody.create(MEDIA_TYPE_MARKDOWN, s);
        Request request = new Request.Builder().url(url).post(body).build();
        try (Response response = client.newCall(request).execute()) {
            LOGGER.debug(STATUS_CODE + response.code());
            if (response.isSuccessful()) {
                result = response.body().string();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOGGER.warn("发送 POST 请求出现异常！" + e);
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                LOGGER.warn("关闭流出现异常！" + ex);
            }
        }
        return result;
    }

    public static String getRequestUrl(HttpServletRequest request) {
        String requestUrl = request.getScheme() + "://"; // 请求协议 http 或 https
        requestUrl += request.getHeader("host"); // 请求服务器
        requestUrl += request.getRequestURI(); // 工程名
        // 判断请求参数是否为空
        if (request.getQueryString() != null) {
            requestUrl += "?" + request.getQueryString(); // 参数
        }
        return requestUrl;
    }
}
